//
//  DCIcloudModule.m
//  LibWeexDCIcloud
//
//  Created by yanyu on 2019/4/24.
//  Copyright © 2019年 yanyu. All rights reserved.
//

#import "DCIcloudModule.h"
#import "WXUtility.h"
#import "FileUtils.h"
#import "iCloudManager.h"

@interface DCIcloudModule()<UIDocumentPickerDelegate>
@property (nonatomic, copy) WXModuleKeepAliveCallback callback;
@end
@implementation DCIcloudModule

@synthesize weexInstance;

WX_EXPORT_METHOD(@selector(openICloud:callback:))

#pragma mark - Export Method


- (void)openICloud:(NSDictionary *)options callback:(WXModuleKeepAliveCallback)callback
{
    _callback = callback;
    NSLog(@"执行");
    if (_callback) {
        _callback(@"",TRUE);
    }
    NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
    UIDocumentPickerViewController *vc = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];

    vc.delegate = self;
    [[self findVisibleVC] presentViewController:vc animated:YES completion:nil];
}

- (UIViewController *)findVisibleVC {
    UIViewController *visibleVc = nil;
    UIWindow *visibleWindow = nil;
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for (UIWindow *window in windows) {
        if (!window.hidden && !visibleWindow) {
            visibleWindow = window;
        }
        if ([UIWindow instancesRespondToSelector:@selector(rootViewController)]) {
            if ([window rootViewController]) {
                visibleVc = window.rootViewController;
                break;
            }
        }
    }
    
    return visibleVc ?: [[UIApplication sharedApplication].delegate window].rootViewController;
}

#pragma mark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls{
    NSMutableArray *arr = [NSMutableArray array];
    for (NSURL *url in urls) {
        NSArray *array = [[url relativeString] componentsSeparatedByString:@"/"];
        NSString *fileName = [array lastObject];
        fileName = [fileName stringByRemovingPercentEncoding];
        NSLog(@"文件路径:%@",[url relativeString]);
        
//        NSURL *ab = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:@"com.simple.Jasmine"];
//        
//        NSURL *ubiquityURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:@"com.simple.Jasmine"];
//        
//        //验证iCloud是否可用
//        
//        if(!ubiquityURL)
//            
//        {
//            
//            NSLog(@"尚未开启iCloud功能");
//            
//            
//        }

        
        NSString *path = url.absoluteString; // 完整的url字符串
        __weak typeof(self) weakself = self;
        [iCloudManager downloadWithDocumentURL:url callBack:^(NSData * _Nonnull obj) {
            NSData *data = obj;
            //写入文件到file中
            [self createFileDirectories];
            
//            NSString *suff = [path pathExtension];
            NSString *name = [[NSFileManager defaultManager] displayNameAtPath:path];//[name stringByAppendingString:[NSString stringWithFormat:@".%@",suff]];
            name = [name stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *newFilePath = [NSString stringWithFormat:@"%@/%@",[FileUtils newDirector],name];
            BOOL isSuccess =[data writeToFile:newFilePath atomically:TRUE];
            if (isSuccess) {
                [arr addObject:@{@"path":newFilePath ? newFilePath:@""}];
                
                if (weakself.callback) {
                    weakself.callback(arr,TRUE);
                }
            }
        }];

    }
}

- (void)createFileDirectories{
    NSString *filePath = [FileUtils newDirector];
    // 判断存放音频、视频的文件夹是否存在，不存在则创建对应文件夹
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    NSError *error = nil;
    if(!(isDirExist && isDir))
        
    {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:TRUE attributes:nil error:&error];
        if(!bCreateDir){
            
            NSLog(@"Create Audio Directory Failed.");
            
        }
        
        NSLog(@"%@",filePath);
        
    }
}

@end
